/**
 * @Author: colpu
 * @Date: 2025-03-29 17:57:34
 * @LastEditors: colpu ycg520520@qq.com
 * @LastEditTime: 2025-05-30 13:43:06
 * @
 * @Copyright (c) 2025 by colpu, All Rights Reserved.
 */
import path from "node:path";
import _ from "lodash";
import { readJSONSync, loadFile } from "../utils/index.js";
import debugFactory from "debug";
const debug = debugFactory("cli:config");

const defaultENV = process.env.NODE_ENV || "development";

export default async (root, dir = "src", env = defaultENV) => {
  console.time("加载config时间");
  const pkg = readJSONSync(path.join(root, "package.json"));
  const directory = path.join(root, dir, "config");
  const names = ["index.js", `${env}.js`];
  const config = { root };
  for (const filename of names) {
    const filepath = `${directory}/${filename}`;
    if (filepath) {
      const envConfig = await loadFile(filepath);
      _.merge(config, envConfig);
    }
  }
  debug("loadConfig: %s", directory);
  console.timeEnd("加载config时间");

  return {
    name: pkg.name,
    pkg,
    config,
    env,
  };
};
